<!--
* description:垂直媒体-店端主动录入
* author: liks
* createdDate: 2020-05-05
-->
<template>
  <section class="editCarBrand">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      @close="sendCode"
      width="1000px"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :styleType="$store.state.app.dialogType"
      ></dialogHeader>
      <div class="filter-container filter-params-crm">
        <el-row :gutter="26">
          <component
            v-for="comp in tableComponents.filter(o => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
            :validrule="comp.validrule"
            :key="comp.compKey"
            :codeField="comp.codeField"
            :textField="comp.textField"
            :popupsKey="comp.compKey"
            :is="comp.component"
            :isMul="comp.isMul"
            :code="formField[comp.codeField]"
            :text="formField[comp.textField]?formField[comp.textField]:fakeField[comp.textField]"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
            @emitCode="comp.emitCode"
            @getCode="comp.changeCode"
            :disabled="comp.disabled"
            :isRequire="comp.isRequire"
            :span="comp.span || 8"
            :dateType="comp.dateType"
            :labelName="comp.labelName"
            :lookuptype="comp.lookuptype"
            :dateOptionsType="comp.dateOptionsType"
            :inputType="comp.inputType"
            :attribute="comp.attribute"
          ></component>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          @click="comp.clickEvent"
        >{{comp.text}}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from "@/components/mixins/formMixins";
import { crmApis } from "@/api/apiList/crm";
import { requestAPI } from "@/api/commonRequest";
export default {
  // 组件混入对象
  mixins: [formMixins],
  components: {
    dialogHeader: () => import("@/components/dialogHeader") //弹窗标题
  },
  data() {
    return {
      // 保存API配置对象
      apiConfig: crmApis.clueServerMutationCreateClueOrder,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey3",
          type: "primary",
          size: "small",
          clickEvent: () => this.save(),
          text: "保存"
        }
      ],
      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: "compKey1",
          labelName: "客户名称",
          codeField: "custName",
          isMust: true,
          isRequire: true,
          component: () =>
            import("@/components/crm/textbox/crmTextInput")
        },
        {
          compKey: "compKey2",
          labelName: "电话",
          codeField: "contactTel",
          component: () =>
            import("@/components/crm/crmEjectWindows/crmCallandMsg"),
          inputType: "inputText",
          isRequire: true,
          isMust: true,
          validrule: {
            noRequire: false,
            isformat: /^((0\d{2,3}-\d{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/
          },
        },
        {
          compKey: "compKey3",
          labelName: "性别",
          codeField: "gender",
          lookuptype: "DB0022",
          isRequire: false,
          isMust: true,
          component: () =>
            import("@/components/crm/lookupValue/lookupvalue")
        },
        {
          compKey: "compKey4",
          labelName: "备用电话",
          codeField: "backupTel",
          isRequire: true,
          isMust: true,
          validrule: {
            noRequire: true,
            isformat: /^((0\d{2,3}-\d{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/
          },
          component: () =>
            import("@/components/crm/textbox/crmTextInput")
        },
        // {
        //   compKey: "compKey5",
        //   labelName: "信息来源",
        //   codeField: "infoChanDCode",
        //   textField: "infoChanName",
        //   isRequire: true,
        //   isMust: true,
        //   component: () =>
        //     import(
        //       "@/components/crm/crmEjectWindows/crmSourceFrom/index"
        //     ),
        //   type: "propus",
        //   emitCode: (rowData, _this) =>
        //     this.changeSource(rowData, _this)
        // },
        {
          compKey: "compKey5",
          labelName: "二级信息来源",
          codeField: "infoChanDName",
          isMust: true,
          isRequire: true,
          component: () =>
            import("@/components/crm/textbox/crmTextInput")
        },
        {
          compKey: "compKey6",
          labelName: "意向级别",
          codeField: "clueLevelCode",
          lookuptype: "LX141",
          attribute: "1",
          isMust: true,
          component: () =>
            import("@/components/crm/lookupValue/lookupvalue"),
          changeCode: this.levelChange
        },
        {
          compKey: "compKey7",
          labelName: "意向车系",
          codeField: "inteSeriesCode",
          textField: "carSeriesCn",
          emitCode: rowData => this.getCarSeries(rowData),
          component: () =>
            import(
              "@/components/crm/crmEjectWindows/crmIntenCarSeries/index"
            ),
          inputType: "inputText",
          isMust: true,
        },
        {
          compKey: "compKey8",
          labelName: "意向车型",
          codeField: "inteTypeCode",
          textField: "inteTypeName",
          emitCode: rowData => this.getCarType(rowData),
          component: () =>
            import(
              "@/components/crm/crmEjectWindows/crmCartype/index"
            ),
          inputType: "inputText",
          isMust: true,
        },

        {
          compKey: "compKey9",
          labelName: "下次回访时间",
          codeField: "nextCallbackDate",
          isMust: true,
          component: () =>
            import("@/components/crm/Time/crmafterDateTime")
        },
        {
          compKey: "compKey10",
          labelName: "描述",
          codeField: "clueDesc",
          inputType: "textarea",
          span: 16,
          isMust: true,
          component: () =>
            import("@/components/crm/textbox/crmTextInput")
        },
        {
          compKey: "compKey11",
          labelName: "备注",
          codeField: "remark",
          inputType: "textarea",
          span: 16,
          isMust: true,
          component: () =>
            import("@/components/crm/textbox/crmTextInput")
        }
      ],
      // 标题
      textMap: {
        edit: "垂直媒体-店端主动录入",
        add: "垂直媒体-店端主动录入"
      },
      // 表单数据（无需赋值，由混入对象赋值）
      formField: {
        dlrCode: this.$store.getters.orgInfo.DLR_CODE,
        createType:"1",//垂直媒体参数
        custName: "",
        gender: "",
        contactTel: "",
        backupTel: "",
        clueLevelCode: "",
        nextCallbackDate: "",
        inteSeriesCode: "",
        inteSeriesId: "",
        inteTypeCode: "",
        inteTypeId: "",
        inteTypeName: "",
        clueDesc: "",
        remark: "",
        handleCode: "1",
        carBrandCode: "",
        carBrandName: "",
        infoChanDName: "",
        carSeriesCn: "",
      },
      //只作显示，不实际传参的字段
      fakeField: {

      },
      aArriveReview: "",
      bArriveReview: "",
      hArriveReview: "",
      crmSourceFromThis:"",
    };
  },
  mounted() {
    console.log(this.$store.getters.orgInfo);
    this.$nextTick(function() {
      this.getFactSysConf();
    });
  },
  methods: {
    //获取系统配置
    getFactSysConf() {
      let that = this;
      let queryObj = {
        type: "query",
        // api配置
        apiConfig: crmApis.csDbSystemConfigQueryHost,
        // 需要调用的API服务配置
        apiServices: [
          {
            //表格中台返回网格的字段
            apiQueryRow: [
              "oemClueAssgin",
              "oemClueRecoverTime",
              "clueAutoNotInvalid",
              "firstReviewKpi",
              "aArriveReview",
              "bArriveReview",
              "cArriveReview",
              "eArriveReview",
              "hArriveReview",
              "validClue",
              "invalidClue",
              "cluePools",
              "oemCode",
              "oemId",
              "updateControlId",
              "systemConfigId",
              "isDcc",
              "clueAutoInvalid",
              "failContrloIsCheck"
            ]
          }
        ],
        //条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          pageSize: 10,
          pageIndex: 1,
          //当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: {
            oemId: this.$store.getters.orgInfo.OEM_ID //根据厂家ID去查找--this.$store.getters.orgInfo
          }
        }
      };
      //转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      requestAPI(paramD).then(response => {
        if (
          response.result == "1"
          //&&response.rows != ""
        ) {
          let results = response.rows[0];
          this.aArriveReview = results["aArriveReview"];
          this.bArriveReview = results["bArriveReview"];
          this.hArriveReview = results["hArriveReview"];
          this.levelChange(this.formField.clueLevelCode);
        }
      });
    },
    //意向级别change
    levelChange(val) {
      debugger
      console.log(val);
      let curDate = new Date().getTime();
      if (val == "A") {
        this.formField.nextCallbackDate = this.transformTime(
          new Date(curDate + this.aArriveReview * 24 * 3600 * 1000)
        );
      } else if (val == "B") {
        this.formField.nextCallbackDate = this.transformTime(
          new Date(curDate + this.bArriveReview * 24 * 3600 * 1000)
        );
      } else if (val == "H") {
        this.formField.nextCallbackDate = this.transformTime(
          new Date(curDate + this.hArriveReview * 24 * 3600 * 1000)
        );
      } else {
        this.formField.nextCallbackDate = "";
      }
    },
    transformTime(time) {
      var y = time.getFullYear();
      var M = time.getMonth() + 1;
      var d = time.getDate();
      // var h = time.getHours();
      // var m = time.getMinutes();
      // var s = time.getSeconds();
      return (
        y + "-" + this.addZero(M) + "-" + this.addZero(d) + " " + "00:00:00"
      );
    },
    addZero(m) {
      return m < 10 ? "0" + m : m;
    },
    //获取意向车型弹出框返回值
    getCarType(rowData) {
      let results = rowData[0];
      this.formField.inteTypeCode = results["smallCarTypeCode"];
      this.formField.inteTypeId = results["smallCarTypeId"];
      this.formField.inteTypeName = results["smallCarTypeCn"];
      this.formField.inteSeriesCode = results["carSeriesCode"];
      this.formField.inteSeriesId = results["carSeriesId"];
    },
    // 获取意向车系
    getCarSeries(rowData) {
      this.formField.inteTypeCode=''
      let results = rowData[0];
      this.formField.inteSeriesCode = results["carSeriesCode"];
      this.formField.inteSeriesId = results["carSeriesId"];
      this.formField.carBrandCode = results["carBrandCode"];
    },
    //渠道来源
    changeSource(rowData, _this) {
      let results = rowData[0];
      this.formField.cantactWayCode = results.cantactWayCode;
      this.formField.infoChanMCode = results.infoChanMCode;
      this.formField.infoChanDCode = results.infoChanDCode;
      // this.crmSourceFromThis = _this;
      this.formField.infoChanName=results.cantactWayName+'->'+results.infoChanMName+'->'+results.infoChanDName;
    },
    //保存
    save() {
      const that = this;
      that.$utils.validataMoth(that, "validpopup");
      var html = "";
      if (that.$utils.isEmpty(that.formField.custName)) {
        html = html + `<div class="sys-alertDiv"s>客户名称不能为空</div>`;
      }
      if (that.$utils.isEmpty(that.formField.contactTel)) {
        html = html + `<div class="sys-alertDiv">电话不能为空</div>`;
      }
      if (that.$utils.isEmpty(that.formField.infoChanDName)) {
        html = html + `<div class="sys-alertDiv">二级信息来源不能为空</div>`;
      }

      if (html != "") {
        this.$crmcf.showMessages(this, "error", html, true);
        return;
      }
      //保存表单
      if (that.formField.mileage === "") {
        that.formField.mileage = undefined;
      }
      if (typeof that.formField.mileage == "string") {
        that.formField.mileage = parseFloat(that.formField.mileage);
      }
      //剔除中台不需要的参数，同时不影响弹窗的显示值
      if (that.fakeField) {
        for (let key in that.fakeField) {
          if (that.formField[key]) {
            that.fakeField[key] = that.formField[key];
            delete that.formField[key];
          }
        }
      }
      if(that.formField.clueLevelCode==''){
        that.formField.clueLevelCode=null
      }
      let vaild = true;
      let vaildParams = {
        custName: [
          "simpleName",
          that.formField.custName,
          `<div>请输入2~20个字的客户名称</div>`
        ],
        contactTel: [
          "telOrphone",
          that.formField.contactTel,
          `<div>请输入正确的电话（手机或座机号码）！</div>`
        ],
        backupTel: [
          "telOrphone",
          that.formField.backupTel,
          `<div>请输入正确的备用电话（手机或座机号码）！</div>`
        ],
      };
      vaild = this.$crmcf.regex(this, vaildParams);
      if (!vaild) {
        return;
      }
      // this.saveForm();
      let queryObj = {
        // api配置
        type: "mutation",
        apiConfig: crmApis.clueServerMutationCreateClueOrder,

        //条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          //当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: that.formField
        }
      };
      //转换了中台请求格式数据
      var paramD = that.$getParams(queryObj);
      // 调用中台API方法（可复用）
      requestAPI(paramD).then(response => {
        if (
          response.result == "1"
          // &&response.rows != ""
        ) {
          that.$crmcf.showMessages(that, "success", "保存成功！");
          that.curPopupsVisible=false;
        } else {
          that.$crmcf.showMessages(
            that,
            "error",
            response.msg
          );
        }
      });
    },

  }
};
</script>
